const fs = require('fs');
const fpath = require('path');
const loadLocalHtml = function (fileNme) {
    const path = fpath.join(__dirname, '../html_store', fileNme + '.html')
    if (exist(path)) {
        // 文件存在
        return fs.readFileSync(path, 'utf8');
    }
    return undefined;
}

const exist = function (path) {
    try {
        fs.accessSync(path)
    } catch (err) {
        return false;
    }
    return true;
}

const writeHtml = function (content, fileName) {
    const path = fpath.join(__dirname, '../html_store', fileName + '.html')
    if (!(typeof (content) === 'string')) {
        content = JSON.stringify(content, null, 4);
    }
    fs.writeFileSync(path, content)
}

const loadLocalConfig = function (tag) {
    try {
        var content = fs.readFileSync(fpath.join(__dirname, '../config', tag + '.json'))
        var json = JSON.parse(content);
        return json;
    } catch (error) {
        return undefined;
    }
}
function loadConfigs() {
    var files = [];
    var parentPath = fpath.join(__dirname, "../config")
    fs.readdirSync(parentPath).forEach(item => {
        files.push(fpath.join(parentPath, item))
    });
    var configs = [];
    for (let index = 0; index < files.length; index++) {
        const path = files[index];
        const content = fs.readFileSync(path, 'utf8');
        const jsonBean = JSON.parse(content);
        delete jsonBean.host;
        configs.push(jsonBean);
    }
    return configs;
}
module.exports = { loadLocalHtml, writeHtml, loadLocalConfig, exist, loadConfigs }